import React, { lazy, Suspense, useEffect, useState } from 'react'
import { 
  Card, Button, Input, Space, Tag, Spin, message, Modal, 
  Flex, Typography, Pagination, Checkbox, Badge, Tooltip, 
  type SpinProps
} from 'antd'
import { 
  FolderAddOutlined, SearchOutlined, UserOutlined, 
  ZoomOutOutlined, EditOutlined, DeleteOutlined, 
  ReloadOutlined, FilterOutlined, FileProtectOutlined,
  FileAddOutlined, MoreOutlined,
  DiffOutlined,
  ContainerOutlined,
  SecurityScanOutlined
} from '@ant-design/icons'
import http from '../api/http'
import type { IGanyux } from '~/types/ganyux';
import dayjs from 'dayjs';
import './UsersCardLayout.css';

const { Title, Text, Paragraph } = Typography;

const Users: React.FC = () => {
  // 表格选择相关
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 状态管理
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState<boolean | SpinProps>({
    size: 'large',
    tip: '数据加载中...'
  });
  const [count, setCount] = useState(0);
  const [data, setData] = useState<Array<IGanyux>>([]);
  const [inputvalue, setvalue] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(2);
  const [loadings, setLoadings] = useState<boolean[]>([]);
  const [loadings1, setLoadings1] = useState<boolean[]>([]);
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const [hoveredCardId, setHoveredCardId] = useState<number | null>(null);
const AddUserForm = lazy(() => import('./add'));
const AddUserForm1 = lazy(() => import('./chax'));
const [isModalOpen1, setIsModalOpen1] = useState(false);
  const handleCance2 = () => {
    setIsModalOpen1(false);
  };
    const handleAddSuccess1 = () => {
    setIsModalOpen1(false);
    fetchUsers(1, pageSize); // 新增成功后刷新数据
  };
    const [pageValue, setPageValue] = useState(2);
  const xian=(zz:number)=>{
    console.log('bb',zz)
   setPageValue(zz)
    setIsModalOpen1(true);
  }
  // 获取用户数据
  const fetchUsers = async (page: number, size: number) => {
    setLoading({ size: 'large', tip: '数据加载中...' });
    
    try {
      const response = await http.getList<IGanyux>('Ganyux', { 
        page, 
        size, 
        name: inputvalue 
      });
      console.log('tt',response.data)
      setData(response.data || []);
      setCount(response.count || 0);
    } catch (error) {
      message.error('数据加载失败，请重试');
      console.error('加载失败:', error);
    } finally {
      setTimeout(() => {
        setLoading(false);
      }, 200);
    }
  };

  // 搜索输入处理
  const changeCount1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    setvalue(event.target.value);
  };

  // 初始化数据
  useEffect(() => {
    fetchUsers(1, pageSize);
  }, []);

  // 刷新数据触发
  useEffect(() => {
    fetchUsers(currentPage, pageSize);
  }, [refreshTrigger]);

  // 加载状态处理
  const enterLoading = (index: number) => {
    setLoadings(prev => {
      const newLoadings = [...prev];
      newLoadings[index] = true;
      return newLoadings;
    });

    setTimeout(() => {
      setLoadings(prev => {
        const newLoadings = [...prev];
        newLoadings[index] = false;
        return newLoadings;
      });
      setIsModalOpen(true);
    }, 500);
  };

  // 搜索处理
  const enterLoading1 = (index: number) => {
    setLoadings1(prev => {
      const newLoadings = [...prev];
      newLoadings[index] = true;
      return newLoadings;
    });

    setTimeout(() => {
      setLoadings1(prev => {
        const newLoadings = [...prev];
        newLoadings[index] = false;
        return newLoadings;
      });
      fetchUsers(1, pageSize);
      setCurrentPage(1);
    }, 500);
  };

  // 模态框处理
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleAddSuccess = () => {
    setIsModalOpen(false);
    setRefreshTrigger(prev => prev + 1);
    message.success('新增成功');
  };

  // 删除处理
  const delUser = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条记录吗？此操作不可撤销',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        message.success(`ID: ${id} 删除成功！`);
        setRefreshTrigger(prev => prev + 1);
      }
    });
  };

  // 分页处理
  const handleTableChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    fetchUsers(page, size);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 全选处理
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedRowKeys(data.map(item => item.id));
    } else {
      setSelectedRowKeys([]);
    }
  };

  // 单选处理
  const handleSelect = (id: React.Key, checked: boolean) => {
    if (checked) {
      setSelectedRowKeys([...selectedRowKeys, id]);
    } else {
      setSelectedRowKeys(selectedRowKeys.filter(key => key !== id));
    }
  };

  // 刷新处理
  const handleRefresh = () => {
    const refreshBtn = document.querySelector('.refresh-btn');
    refreshBtn?.classList.add('refreshing');
    fetchUsers(currentPage, pageSize).then(() => {
      setTimeout(() => {
        refreshBtn?.classList.remove('refreshing');
      }, 500);
    });
  };

  // 状态标签渲染
  const renderStatusTag = (value: number) => {
    if (value === 0) {
      return (
        <Tag icon={<FileProtectOutlined />} color="success">
          正常
        </Tag>
      );
    } else if (value === 1) {
      return (
        <Tag icon={<ContainerOutlined />} color="warning">
          轻度
        </Tag>
      );
    } else if (value === 2) {
      return (
        <Tag icon={<SecurityScanOutlined />} color="processing">
          中度
        </Tag>
      );
    } else if(value === 3){
        return (
        <Tag icon={<FileAddOutlined />} color="error">
          偏重
        </Tag>
        )
    } else if(value === 4){
        return (
         <Tag icon={<DiffOutlined />} color="error">
          严重
        </Tag>
          )
    }
    return <Tag color="default">未知</Tag>;
  };

  return (
  
    <div className="page-container">
      {/* 页面标题 */}
        <div>
                  <Modal
                  title="添加用户"
                  open={isModalOpen}
                  onCancel={handleCancel}
                  maskClosable={false}
                  width={1000}
                  height={400}
                  footer={null} // 禁用默认footer，使用表单内的提交按钮
                >
                  <Suspense fallback={<Spin size="large" style={{ display: 'block', margin: '20px auto' }} />}>
                    {/* 渲染添加页面组件，并传递必要的props */}
                    <AddUserForm 
                      onSuccess={handleAddSuccess} 
                      onCancel={handleCancel} 
                    />
                  </Suspense>
                </Modal>

                   <Modal
                        title="查询"
                        open={isModalOpen1}
                        onCancel={handleCance2}
                        maskClosable={false}
                        width={1000}
                        footer={null}
                      >
                        <Suspense fallback={<Spin size="large" style={{ display: 'block', margin: '20px auto' }} />}>
                          <AddUserForm1 
                            onSuccess={handleAddSuccess1} 
                            onCancel={handleCance2} 
                             value={pageValue} 
                          />
                        </Suspense>
                      </Modal>
        </div>
      {/* 操作工具栏 */}
      <Card className="operation-card" bordered={false}>
        <Flex align="center" justify="space-between" wrap>
          <Space size="middle" className="operation-buttons">
            <Button
              type="primary"
              size="middle"
              icon={<FolderAddOutlined />}
              loading={loadings[1]}
              onClick={() => enterLoading(1)}
              className="add-button"
            >
              新增心测
            </Button>
            
            <Button
              size="middle"
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              className="refresh-btn"
            >
              刷新
            </Button>
            
            <Button
              size="middle"
              icon={<FilterOutlined />}
              className="filter-btn"
            >
              筛选
            </Button>
          </Space>

          <Space size="middle" className="search-container">
            <Input 
              value={inputvalue} 
              onChange={changeCount1} 
              size="middle" 
              placeholder="档案号/姓名" 
              prefix={<UserOutlined />} 
              className="search-input"
              onPressEnter={() => enterLoading1(1)}
            />
            <Button
              type="primary"
              size="middle"
              icon={<SearchOutlined />}
              loading={loadings1[1]}
              onClick={() => enterLoading1(1)}
              className="search-button"
            >
              查询
            </Button>
          </Space>
        </Flex>

        {/* 选中状态提示 */}
        {selectedRowKeys.length > 0 && (
          <div className="selection-info">
            <Badge count={selectedRowKeys.length} showZero>
              <Text>已选中记录</Text>
            </Badge>
            <Button 
              type="text" 
              danger 
              size="small" 
              onClick={() => setSelectedRowKeys([])}
              className="clear-selection"
            >
              清空选择
            </Button>
          </div>
        )}
      </Card>

      {/* 全选与统计 */}
      {data.length > 0 && (
        <div className="select-all-bar">
          <Checkbox 
            checked={selectedRowKeys.length === data.length && data.length > 0}
            indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < data.length}
            onChange={(e) => handleSelectAll(e.target.checked)}
          >
            全选当前页
          </Checkbox>
          <Text className="total-count">共 {count} 条记录</Text>
        </div>
      )}

      {/* 卡片列表 */}
      {loading ? (
        <div className="loading-container">
          <Spin {...(loading as SpinProps)} />
        </div>
      ) : data.length > 0 ? (
        <div className="card-grid">
          {data.map((item) => (
            <Card 
              key={item.id}
              className={`data-card ${hoveredCardId === item.id ? 'hovered' : ''}`}
              onMouseEnter={() => setHoveredCardId(item.id)}
              onMouseLeave={() => setHoveredCardId(null)}
              bordered={false}
            >
              {/* 卡片头部 */}
              <div className="card-header">
                <Checkbox 
                  checked={selectedRowKeys.includes(item.id)}
                  onChange={(e) => handleSelect(item.id, e.target.checked)}
                  className="card-checkbox"
                />
                <div className="card-header-info">
                  <div className="file-number">档案号: {item.fileNumber}</div>
                  <div className="评估日期">
                    评估日期: {item.xdata ? dayjs(item.xdata).format('YYYY-MM-DD') : '-'}
                  </div>
                </div>
              </div>

              <div className="card-divider"></div>

              {/* 卡片主体 */}
              <div className="card-body">
                <div className="user-info">
                  <div className="user-name">
                    {item.name}
                    <Tag className="gender-tag" color={item.sex === '男' ? 'blue' : 'pink'}>
                      {item.sex}
                    </Tag>
                  </div>
                </div>

                {/* 评估指标 */}
                <div className="assessment-grid">
                  <div className="assessment-item">
                    <Text className="item-label">躯体化:</Text>
                    {renderStatusTag(item.xin || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">强迫症化:</Text>
                    {renderStatusTag(item.xin1 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">人际关系敏感:</Text>
                    {renderStatusTag(item.xin2 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">犹豫:</Text>
                    {renderStatusTag(item.xin3 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">焦虑:</Text>
                    {renderStatusTag(item.xin4 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">敌对:</Text>
                    {renderStatusTag(item.xin5 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">恐怖:</Text>
                    {renderStatusTag(item.xin6 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">偏执:</Text>
                    {renderStatusTag(item.xin7 || 0)}
                  </div>
                  <div className="assessment-item">
                    <Text className="item-label">精神病性:</Text>
                    {renderStatusTag(item.xin8 || 0)}
                  </div>
                </div>
              </div>

              <div className="card-divider"></div>

              {/* 操作按钮 */}
              <div className="card-actions">
                <Tooltip title="查看详情">
                  <Button 
                    type="text" 
                    icon={<ZoomOutOutlined />} 
                    className="action-btn view-btn"
                    onClick={()=>xian(item.id)}
                  />
                </Tooltip>
                <Tooltip title="修改">
                  <Button 
                    type="text" 
                    icon={<EditOutlined />} 
                    className="action-btn edit-btn"
                  />
                </Tooltip>
                <Tooltip title="删除">
                  <Button 
                    type="text" 
                    icon={<DeleteOutlined />} 
                    className="action-btn delete-btn"
                    onClick={() => delUser(item.id)}
                  />
                </Tooltip>
              </div>
            </Card>
          ))}
        </div>
      ) : (
        <Card className="empty-card" bordered={false}>
          <div className="empty-state">
            <div className="empty-icon">📊</div>
            <h3 className="empty-title">暂无体测记录</h3>
            <p className="empty-desc">当前没有任何体测数据，请添加新的记录</p>
            <Button 
              type="primary" 
              icon={<FolderAddOutlined />}
              onClick={() => enterLoading(1)}
              className="empty-add-btn"
            >
              新增体测记录
            </Button>
          </div>
        </Card>
      )}

      {/* 分页 */}
      {count > 0 && (
        <div className="pagination-container">
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={count}
            onChange={handleTableChange}
            showTotal={(total) => `共 ${total} 条记录`}
            showSizeChanger
            showQuickJumper
            pageSizeOptions={['2', '5', '10', '20']}
            className="custom-pagination"
          />
        </div>
      )}

      {/* 新增体测模态框 */}
   
    </div>
  );
};

export default Users;